# -*- coding: utf-8 -*-
import json

from django.utils.decorators import method_decorator
from django.views.decorators.http import require_POST, require_GET
from django.views.generic import TemplateView

from common.admin.db import get_user
from common.agentpay import db as agentpay_db
from common.channel import admin_db as channel_admin_db
from common.channel.admin_db import get_channel
from common.channel.model import CHANNEL_TYPE
from common.channel.pay import mepay, peiqipay, xunlianpay, kvpay, newchuangpupay, amazepay, xlbpay, ttpay
from common.settlement.db import get_bankcard_by_card_num, get_bankcard_list
from common.utils import track_logging
from common.utils.api import token_required, check_agent_params
from common.utils.decorator import response_wrapper
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

CHANNEL_MAP = {
    CHANNEL_TYPE.PEIQIPAY: peiqipay.handler,
    CHANNEL_TYPE.MEPAY: mepay.handler,
    CHANNEL_TYPE.XUNLIANPAY: xunlianpay.handler,
    CHANNEL_TYPE.KVPAY: kvpay.handler,
    CHANNEL_TYPE.NEWCHUANGPUPAY: newchuangpupay.handler,
    CHANNEL_TYPE.AMAZEPAY: amazepay.handler,
    CHANNEL_TYPE.XLBPAY: xlbpay.handler,
    CHANNEL_TYPE.TTPAY: ttpay.handler,
}


class AgentPayOrderView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()

        items, total_count = agentpay_db.list_order(query_dct)

        agentpay_list = []
        for item in items:
            # _LOGGER.info('item>>>>>>>>>>>>>>>>%s' % item.as_dict())

            item_dict = item.as_dict()
            item_dict['total_fee'] /= 100
            item_dict['admin_name'] = get_user(item_dict['operator_id']).nickname

            card_no = item_dict['card_no'][4:15]
            new_card_no = item_dict['card_no'].replace(card_no, '*************')
            item_dict['card_no'] = new_card_no

            phone_number = item_dict['phone_number'][4:7]
            new_phone_number = item_dict['phone_number'].replace(phone_number, '****')
            item_dict['phone_number'] = new_phone_number

            identity_card = item_dict['identity_card'][4:14]
            new_identity_card = item_dict['identity_card'].replace(identity_card, '*************')
            item_dict['identity_card'] = new_identity_card

            agentpay_list.append(item_dict)

        return {'list': agentpay_list,
                'total': total_count, 'page': query_dct.get('$page', 1),
                'size': len(items)}

    def post(self, req):
        operator_id = req.user.id
        try:
            json.loads(req.body)
            param_dct = json.loads(req.body)
        except:
            _LOGGER.info("im here")
            param_dct = dict(req.POST.iteritems())

        for e in ('card_num', 'channel_id', 'chn_type', 'platform', 'total_fee', 'unionpay_no'):
            if e not in param_dct:
                raise ParamError(u'请完善新增代付信息')

        bank_param = {}
        card_num = param_dct['card_num']
        bank_card = get_bankcard_by_card_num(card_num)

        if bank_card.status is not None and bank_card.status != 1:
            raise ParamError(u'当前银行卡不可用')
        if 'total_fee' not in param_dct and int(float(param_dct['total_fee'])) > 50000:
            raise ParamError(u'金额无效或金额不可大于五万')

        channel_id = param_dct['channel_id']

        channel = get_channel(channel_id)
        if not channel:
            raise ParamError('channel do not exists')

        _LOGGER.info("channel.chn_type is: %s", channel.chn_type)
        bank_param['total_fee'] = int(float(param_dct['total_fee']))
        bank_param['bank_code'] = bank_card.bank
        bank_param['card_no'] = bank_card.account_number
        bank_param['account_name'] = bank_card.account_holder
        bank_param['phone_number'] = bank_card.phone_num
        bank_param['bank_name'] = bank_card.subbranch
        bank_param['identity_card'] = bank_card.identity_card
        bank_param['account_province'] = bank_card.bank_province
        bank_param['account_city'] = bank_card.bank_city
        bank_param['unionpay_no'] = param_dct['unionpay_no']
        check_agent_pay_param(channel.chn_type, bank_param)

        handler = CHANNEL_MAP[channel.chn_type]
        bankcard = agentpay_db.BankCard(bank_param['bank_code'], bank_param['card_no'], bank_param['account_name'],
                                        bank_param['phone_number'], bank_param['bank_name'],
                                        bank_param['identity_card'], bank_param['account_province'],
                                        bank_param['account_city'], bank_param['unionpay_no'], param_dct['card_num'],
                                        param_dct['chn_type'], param_dct['platform'])
        agentpay_info = handler.create_agent_pay(operator_id, channel_id, bank_param['total_fee'], bankcard)

        return {'agentpay_info': agentpay_info}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(AgentPayOrderView, self).dispatch(*args, **kwargs)


def check_agent_pay_param(chn_type, param_dct):
    if chn_type in [CHANNEL_TYPE.PEIQIPAY, CHANNEL_TYPE.XUNLIANPAY]:
        check_agent_params(param_dct,
                           ['total_fee', 'bank_code', 'card_no', 'account_name', 'phone_number', 'bank_name',
                            'identity_card', 'account_province', 'account_city', 'unionpay_no'])


@require_POST
@token_required
@response_wrapper
def checked_pay_agent(req):
    data = json.loads(req.body)
    order_no = data['order_no']
    agentpay_db.checked_agent_pay_success(order_no)
    return {}


@require_GET
@response_wrapper
def card_num_list(req):
    card_num = get_bankcard_list()
    ret_list = []
    for item in card_num:
        ret_card_num = {}
        ret_card_num.update(
            {'id': item.id, 'card_num': item.card_num, 'platform': item.platform, 'chn_type': item.chn_type,
             'status': item.status})
        ret_list.append(ret_card_num)
    return {'ret_list': ret_list}


@require_POST
@response_wrapper
@token_required
def fresh(req, order_id):
    order_id = int(order_id)
    order = agentpay_db.get_agent_pay_order(order_no=order_id)
    chn = channel_admin_db.get_channel(order.channel_id)
    chn_handler = CHANNEL_MAP[chn.chn_type]
    agentpay_query_info = chn_handler.query_agent_pay(order_id)
    return {'agentpay_query_info': agentpay_query_info}
